package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClassMapper;
import com.itheima.pojo.ClassQueryParam;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Override
    public PageResult classListInfo(ClassQueryParam classQueryParam) {
        PageHelper.startPage(classQueryParam.getPage(),classQueryParam.getPageSize());
        List<Clazz> list = classMapper.lists(classQueryParam);
        LocalDate now = LocalDate.now();
        for (Clazz clazz : list) {
            if( now.isBefore(clazz.getBeginDate())  ){
                clazz.setStatus("未开班");
            }else if( now.isAfter(clazz.getEndDate())  ){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("在读中");
            }

        }

        Page<Clazz> pages =(Page<Clazz>) list;
        long total = pages.getTotal();
        List<Clazz> result = pages.getResult();
        return new PageResult(total,result);
    }

    @Override
    public void addClazz(Clazz clazz) {
        // 设置创建时间和更新时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        // 插入数据
        classMapper.insertClazz(clazz);
    }

    @Override
    public void deleteById(Integer id) {
        classMapper.deleteById(id);
    }

    @Override
    public Clazz getById(Integer id) {
        Clazz clazz = classMapper.getById(id);
        if (clazz != null) {
            clazz.setStatus(calculateStatus(clazz));
        }
        return clazz;
    }

    @Override
    public void updateById(Clazz clazz) {
        // 设置更新时间
        clazz.setUpdateTime(LocalDateTime.now());

        // 更新数据
        classMapper.updateById(clazz);
    }

    @Override
    public List<Clazz> getAllClasses() {
        return classMapper.getAllClasses();
    }

    @Override
    public List<Emp> getAllMasters() {
        return classMapper.getAllMasters();
    }

    /**
     * 计算班级状态
     * @param clazz 班级对象
     * @return 状态字符串
     */
    private String calculateStatus(Clazz clazz) {
        LocalDate now = LocalDate.now();
        if (clazz.getBeginDate().isAfter(now)) {
            return "未开班";
        } else if (clazz.getEndDate().isBefore(now)) {
            return "已结课";
        } else {
            return "已开班";
        }
    }
}
